import ExcelJS from "exceljs";
import { saveAs } from 'file-saver';
import { parseTime } from '.'
/*
 * @description:
 * @param {Object} json 服务端发过来的数据
 * @param {String} name 导出Excel文件名字
 * @param {String} sheetName 导出sheetName名字
 * @return:
 */
export async function exportExcel(jsonData, name, sheetName) {
  /* convert state to workbook */
  const workbook = new ExcelJS.Workbook();
const worksheet = workbook.addWorksheet(sheetName);


  // Assuming jsonData is an array of objects
  const headers = Object.keys(jsonData[0]);
  worksheet.columns = headers.map(header => ({ header, key: header }));

  jsonData.forEach(data => {
    const newRow = worksheet.addRow(data);
    newRow.eachCell({ includeEmpty: true }, cell => {
      cell.font = {
        name: 'Arial',
        size: 10,
      };
    });
  });

  // Optionally set the header's font style
  worksheet.getRow(1).eachCell(cell => {
    cell.font = {
      name: 'Arial',
      size: 10,
    };
  });
// 使用 file-saver 保存文件
const buffer = await workbook.xlsx.writeBuffer();
const blob = new Blob([buffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
saveAs(blob, `${name}-${parseTime(new Date().getTime())}.xlsx`);
}

export async function importExcel(buffer) {
  const workbook = new ExcelJS.Workbook();
  await workbook.xlsx.load(buffer);
  const worksheet = workbook.getWorksheet(1);
  const data = [];
 
  worksheet.eachRow((row, rowNumber) => {
    data.push(row.values);
  });
  
  return data;
}
